<?php
declare(strict_types=1);

namespace App\Utils\Other\AliCloud\Logistics;

use App\Constants\AliCloud\LogisticsCode;
use App\Exception\InternalException;
use App\Exception\InvalidRequestException;
use App\Utils\Http\Request;
use function Hyperf\Config\config;

/**
 * 阿里云物流轨迹接口
 * @author zx
 * @package App\Utils\Other\AliCloud\Logistics
 */
Class Logistics {

    /**
     * 配置
     * @var array|mixed
     */
    protected array $config;

    /**
     * 路径
     * @var string
     */
    protected string $path = '/kdi';

    public function __construct(
        protected Request $request
    )
    {
        $this->config = config('cloud.alicloud.logistics');
    }

    /**
     * 操作
     * @param array $params
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params)
    {
        return $this->request($params);
    }

    /**
     * 请求
     * @param array $params
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function request(array $params)
    {
        $request = $this->request
            ->setHeaders(['Authorization' => "APPCODE {$this->config['app_code']}"])
            ->get($this->config['domain'].$this->path, $params);

        return $this->response($request);
    }

    /**
     * 响应
     * @param $request
     * @return mixed
     */
    protected function response($request)
    {
        logs($request);
        $data = json_decode($request, true);
        if (!$data) {
            throw new InternalException();
        }
        if ($data['status'] != 0) {
            throw new InvalidRequestException(LogisticsCode::getMessage($data['status']));
        }
        return $data['result'];
    }
}